package com.tgy.JUC.producerConsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/***
 * @ClassName: ConditionTest
 * @Description: Condition精准唤醒 A执行完调用B，B调用C，C调用A
 * @Auther: 送你一块二向箔
 * @Date: 10:23 2022/3/11
 * @version : V1.0
 */
public class ConditionTest {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) data3.sayA();
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) data3.sayB();
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) data3.sayC();
        }, "C").start();
    }
}

//资源类
class Data3 {
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private int num = 1;

    public void sayA() {
        lock.lock();
        try {
            //业务，判断-》执行-》通知
            while (num != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>AAAAA");
            num = 2;
            // 唤醒指定的线程，B
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void sayB() {
        lock.lock();
        try {
            while (num != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>BBBBB");
            num = 3;
            // 唤醒指定的线程，C
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void sayC() {
        lock.lock();
        try {
            while (num != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>CCCCC");
            num = 1;
            // 唤醒指定的线程，A
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
